using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Silvery;
using Silvery.Data;
using System.Windows.Media.Imaging;
using ICSharpCode.SharpZipLib.Zip;

namespace RoleEditer
{
    public partial class MainPage : UserControl
    {       
        public static MainPage Current { get; private set; }
        public MainPage()
        {
            InitializeComponent();
            roleCanvas.Children.Add(ANIPlay.Current);
            
            this.AllowDrop = true;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            Current = this;
        }
        //Loaded
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= MainPage_Loaded;
            if (App.Current.IsRunningOutOfBrowser == false)
            {
                MessageBox.Show("此工具需要运行在OutOfBrowser(脱离浏览器)模式下，web版本运行部分功能将不能使用。");
            }
            EditerConfig.Initialization(this);
            packTreeView.SelectedItemChanged += treeViewItem_Selected;
        }
        //对于拖放的支持，可以直接对zip和png解析
        protected override void OnDrop(DragEventArgs e)
        {
            List<FileInfo> spiritList = new List<FileInfo>();
            var filelist = e.Data.GetData("FileDrop") as FileInfo[];
            foreach (var file in filelist)
            {
                if(file.Name.Substring(file.Name.LastIndexOf('.')) == ".zip")
                {
                    spiritList.Add(file);
                }
            }
            if (spiritList.Count>0)
            {
                OpenSpiritFiles(spiritList);
            }
            else
            {

                if (packTreeView.SelectedItem is TreeViewItem_Animat)
                {
                    filelist = e.Data.GetData("FileDrop") as FileInfo[];
                    AddFramesFromFileInfos(filelist);

                }
            }
            base.OnDrop(e);
        }
        //从文件中取得图片
        private void AddFramesFromFileInfos(FileInfo[] filelist)
        {
            if (packTreeView.SelectedItem == null)
            {
                MessageBox.Show("选定一个确定的动画组");
                return;
            }
            if( (packTreeView.SelectedItem is TreeViewItem_Animat) == false)
            {
                MessageBox.Show("指定了不存在动画");
                return;
            }
            List<FileInfo> pnglist = new List<FileInfo>();
            for (int i = 0; i < filelist.Length; i++)
            {
                var file = filelist[i].Name;
                var s = file.Substring(file.LastIndexOf('.'));
                if (s == ".png")
                    pnglist.Add(filelist[i]);
            }
            
            if (pnglist.Count > 0)
            {
                var p = (packTreeView.SelectedItem as TreeViewItem_Animat);
                foreach (var imgfileinfo in pnglist)
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.SetSource(imgfileinfo.OpenRead());
                    var img = new Image() { Source = bitmap };
                    img.Tag = new Point();
                    SpiritManager.Instance[p.ParentSpirit][p.AnimatName].Add(img);

                }
                setFrameStackPanel(SpiritManager.Instance[p.ParentSpirit][p.AnimatName]);
            }
        }
        #region 帧组板操作方法
        //从一个List里设置当前的动画序列
        public void setFrameStackPanel(List<Image> list)
        {
            bool isselfmode = false;
            Image prev = null;
            foreach (var item in list)
            {
                if (IsContainsInFrameStackPanel(item) == false)
                    frameStackPanel.Children.Add(new SpiriteFrame() { Frame = item });
                if (prev != null)
                    if (!EditerConfig.IsImageOffsetPointEqually(prev, item))
                        isselfmode = true;
                prev = item;
            }
            ANIPlay.Current.IsPlaying = false;
            if (ANIPlay.Current.IsPlaying)
                btn_play.Content = "停止";
            else
                btn_play.Content = "播放";
            
            ANIPlay.Current.NowPlayList = list;
            if(isselfmode)
                (offsetModes.Children[0] as RadioButton).IsChecked = true;
        }
        public void SetFrameFromIndex(int index)
        {
            foreach (SpiriteFrame item in frameStackPanel.Children)
            {
                item.IsSelected = false;
            }
            (frameStackPanel.Children[index] as SpiriteFrame).IsSelected = true;
        }
        public void SetFrameFromIndex(SpiriteFrame item)
        {
            SetFrameFromIndex(frameStackPanel.Children.IndexOf(item));
        }
        public int GetFrameIndexFromItem(SpiriteFrame item)
        {
            return frameStackPanel.Children.IndexOf(item);
        }
        //判断是否
        private bool IsContainsInFrameStackPanel(Image img)
        {
            if (img.Parent == null)
                return false;
            else
                return true;
        }
        //帧清理
        private void frameStackPanelChildrenClear()
        {
            for(int i = frameStackPanel.Children.Count - 1;i >=0;i--)
            {
                var item = frameStackPanel.Children[i] as SpiriteFrame;
                item.Dispose();
                frameStackPanel.Children.RemoveAt(i);
            }
        }
        
        //开启和关闭播放
        private void PlayANI_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ANIPlay.Current.IsPlaying = !ANIPlay.Current.IsPlaying;
            if (ANIPlay.Current.IsPlaying)
                btn_play.Content = "停止";
            else
                btn_play.Content = "播放";
        }
        #endregion
        #region 帧的操作，针对于当前动画
        //添加帧的按钮
        private void AddFrames_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "Png Files (.png)|*.png";
            of.Multiselect = true;
            if (of.ShowDialog() == true)
            {
                AddFramesFromFileInfos((FileInfo[])of.Files);
            }
        }
        
        //移除一个帧
        private void RemoveFrame_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (ANIPlay.Current.IsPlaying )
                return;
            var i = ANIPlay.Current.PlayFramesIndex;
            ANIPlay.Current.NowPlayList.RemoveAt(i);
            this.frameStackPanel.Children.RemoveAt(i);
        }
        //帧数向前移动
        private void Frameforward_click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }
        //帧数向后移动
        private void FrameBack_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
        }
        #endregion
        //速度值修改
        private void SpeedValueChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (textTimeSpan == null)
                return;
            int i = 0;
            if (Int32.TryParse(textTimeSpan.Text, out i))
            {
                ANIPlay.Current.Millisecond = i;
                var spirit = SpiritManager.Instance.GetSpiritItem(packTreeView.SelectedItem as TreeViewItem);
                if (spirit != null)
                    spirit.Spirtfile_Fames.Millisecond = i;
            }
            else
                MessageBox.Show("只能填数字，谢谢");
        }
        #region 打开和保存有关的事件和方法
        //保存文件
        private void SaveSpiritFile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (ANIPlay.Current.IsCanControl == false)
                return;
            if (packTreeView.SelectedItem == null || packTreeView.SelectedItem == treeViewItemsRoot)
                return;
            SaveFileDialog sf = new SaveFileDialog();
            sf.Filter = "Spirite Files (.zip)|*.zip";
            if (sf.ShowDialog()== true)
            {       
                var stream = sf.OpenFile();
                SpiritManager.Instance.SaveSpirit(packTreeView.SelectedItem as TreeViewItem, stream);
                stream.Close();
            }
        }

        private void OpenSpiritFile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Multiselect =true;
            of.Filter = "Spirite Files (.zip)|*.zip";
            if (of.ShowDialog() == true)
            {
                OpenSpiritFiles(of.Files);
            }
            
        }
        private void OpenSpiritFiles(IEnumerable<FileInfo> Files)
        {
            foreach (var item in Files)
            {
                try
                {

                    //ZipFile zip = new ZipFile(item.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
                    using (var s = item.OpenRead())
                    {
                        MemoryStream ms = new MemoryStream();
                        s.CopyTo(ms, (int)s.Length);
                        ZipFile zip = new ZipFile(ms);
                        var name = item.Name.Substring(0, item.Name.LastIndexOf(".zip"));
                        var spirit = SpiritManager.Instance.LoadSpirit(zip, name);
                        if (spirit != null)
                            treeViewItemsRoot.Items.Insert(treeViewItemsRoot.Items.Count - 1, spirit);
                        ms.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        //数据写入
        NTableDataWriter DataWriter { get; set; }
        #endregion
        #region 对于动画的操作和设置方法
        //新动画文件操作
        private void NewSpiritFile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SpiritFileNew filenew = new SpiritFileNew();
            filenew.Closed += new EventHandler(filenew_Closed);
            filenew.Show();
        }
        private void Delete_SelectAniItem(object sender, System.Windows.RoutedEventArgs e)
        {
            //删除选定的动画
            if (ANIPlay.Current.IsCanControl == false)
                return;
            if (packTreeView.SelectedItem == treeViewItemsRoot)
                return;
            if (this.packTreeView.SelectedItem != null)
            {
                if (packTreeView.SelectedItem is TreeViewItem)
                {
                    var sitem = packTreeView.SelectedItem as TreeViewItem;
                    if (MessageBox.Show("确定要删除吗？", "删除" + sitem.Header, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        ANIPlay.Current.NowPlayList = null;
                        this.frameStackPanel.Children.Clear();
                        if (sitem is TreeViewItem_Spirite)
                        {
                            SpiritManager.Instance.Remove(sitem);
                            treeViewItemsRoot.Items.Remove(sitem);
                        }
                        else
                        {
                            if (sitem is TreeViewItem_Animat)
                            {
                                var tempAnimat = sitem as TreeViewItem_Animat;
                                SpiritManager.Instance[tempAnimat.ParentSpirit].Remove(tempAnimat.AnimatName);
                                tempAnimat.ParentSpirit.Items.Remove(tempAnimat);
                            }
                        }
                    }
                    
                }
            }
        }
        //新精灵文件
        void filenew_Closed(object sender, EventArgs e)
        {
            var s = (sender as SpiritFileNew);

            s.Closed -= filenew_Closed;
            if (s.DialogResult == true)
            {
                if (SpiritManager.Instance.ContainsSpirit(s.nameTextBox.Text))
                {
                    MessageBox.Show("已经有这个精灵名字了");
                }
                else
                {
                    TreeViewItem_Spirite item = new TreeViewItem_Spirite(s.nameTextBox.Text);

                    treeViewItemsRoot.Items.Insert(treeViewItemsRoot.Items.Count - 1, item);

                    SpiritManager.Instance.Add(item, new NSpiritData());
                }
            }
        }

        
        //重命名选定的动画
        private void Rename_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (ANIPlay.Current.IsCanControl == false)
                return;
            if (packTreeView.SelectedItem is TreeViewItem_Animat && packTreeView.SelectedItem != treeViewItemsRoot)
            {
                Rename_ChildWindow rcw = new Rename_ChildWindow();
                rcw.Show(packTreeView.SelectedItem as TreeViewItem_Animat);
            }
        }
        //当有动画选定的时候
        private void treeViewItem_Selected(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
        {
            if (packTreeView == null)
                return;
            if (e.NewValue is Button)
                return;
            if (e.NewValue is TreeViewItem)
            {
                frameStackPanelChildrenClear();
                var t1 = e.NewValue as TreeViewItem_Animat;
                if (t1 != null)
                {
                    ANIPlay.Current.NowPlayList = SpiritManager.Instance[t1.ParentSpirit][t1.AnimatName];
                    setFrameStackPanel(SpiritManager.Instance[t1.ParentSpirit][t1.AnimatName]);
                    textTimeSpan.Text = t1.ParentSpirit.Spirtfile_Fames.Millisecond.ToString();
                }
                else
                {
                    var t2 = e.NewValue as TreeViewItem_Spirite;
                    if (t2 != null)
                    {
                    }
                }
            }
        }
        #endregion
        #region 偏移有关的事件和方法
        //输出点击，会设置偏移点,这是一个比较粗的做法
        private void ImageOutPanel_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (ANIPlay.Current.IsCanControl == false)
                return;
            var pt = e.GetPosition(ImageOutPanel);
            var Originx =  ImageOutPanel.ActualWidth / 2;
            var Originy = ImageOutPanel.ActualHeight / 2;
            var offsetpt = (Point)ANIPlay.Current.NowPlayList[ANIPlay.Current.PlayFramesIndex].Tag;
            Originx = pt.X - Originx - offsetpt.X;
            Originy =pt.Y - Originy - offsetpt.Y;
            offsetX.Text = ((int)Originx).ToString();
            offsetY.Text = ((int)Originy).ToString();
            
        }
        //偏移点模式设定的选项
        private void offsetModes_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            if (offsetModes == null)
                return;
            for (int i = 0; i < offsetModes.Children.Count; i++)
            {
                if ((offsetModes.Children[i] as RadioButton).IsChecked == true)
                {
                    EditerConfig.OffsetMode = (OffsetMode)i;
                    break;
                }
            }
        }
        //X偏移位置，正数是负数
        private void OffsetXValueChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (offsetX == null)
                return;
            getOffsetFromText();
        }
        //Y偏移位置,正数是负数
        private void OffsetYValueChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (offsetY == null)
                return;
            getOffsetFromText();
        }
        //从设定的文字中取得偏移位置
        void getOffsetFromText()
        {
            if (OffsetValueLocked)
                return;
            int x = 0;
            if (Int32.TryParse(offsetX.Text, out x) == false)
            {
                MessageBox.Show("只能填数字，谢谢");
                return;
            }
            int y = 0;
            if (Int32.TryParse(offsetY.Text, out y) == false)
            {
                MessageBox.Show("只能填数字，谢谢");
                return;
            }

            if ((offsetModes.Children[0] as RadioButton).IsChecked == true)
            {
                ANIPlay.Current.NowPlayList[ANIPlay.Current.PlayFramesIndex].Tag = new Point(-x, -y);
                ANIPlay.Current.UpdataOffset();
            }
            else
            {
                ANIPlay.Current.UpdataOffset(new Point(-x, -y));
            }
        }
        //偏移锁定
        bool OffsetValueLocked = false;
        //偏移位置变化，用给其他的使用
        public void ChangeOffsetValue(Point pt)
        {
            OffsetValueLocked = true;
            offsetX.Text = pt.X.ToString() ;
            offsetY.Text = pt.Y.ToString();
            OffsetValueLocked = false;
        }
        
        #endregion
        
    }
}
